package com.book.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.mapper.CartMapper;
import com.book.pojo.Cart;
import com.book.pojo.CartVo;
import com.book.pojo.UserCartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class CartService extends ServiceImpl<CartMapper, Cart>{

    @Autowired
    private CartMapper cartMapper;

    //多表联查是自定义方法，所以这里要手动调用
    //根据用户id查询购物车记录
    public List<CartVo> findCartByUserId(Integer userId){
        return cartMapper.findCartListByUserId(userId);
    }

    //根据购物车选中的ids 查询对应的记录
    public List<CartVo> findCartByIds(String ids){
        String[] idArray = ids.split(",");  //分割字符串
        return cartMapper.findCartListByIds(Arrays.asList(idArray));  //Arrays.asList() 将数组转化为list
    }

    //统计用户当前购物车商品的总价格
    public double getCartIteamTotal(List<CartVo> list){
        double sum = 0.0;

        for (CartVo cartVo : list) {
            double result = cartVo.getCount() * cartVo.getNewPrice();
            sum += result;
        }

        //解决浮点数计算问题（把计算结果进行格式化处理）
        DecimalFormat df = new DecimalFormat("#.0");
        return Double.parseDouble(df.format(sum));
    }

    //批量删除
    public String batchDelete(String ids){
        if(ids != null){
            String[] idArray = ids.split(",");  //分割字符串
            cartMapper.deleteBatchIds(Arrays.asList(idArray));  //Arrays.asList() 将数组转化为list
        }
        return "success";
    }

    // 包装用户购物车信息数据
    public UserCartVo wrapperCart(List<CartVo> list){
        UserCartVo userCartVo = new UserCartVo();
        userCartVo.setNum(list.size());  ////查询该用户当前购物车物品
        userCartVo.setTotalPrice(getCartIteamTotal(list));      //计算当前购物车物品的价格
        return userCartVo;
    }
}
